package com.shiqla.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Desc ${DESC}
 * Auth Shinelon
 * Date 2018/4/24
 */
public class NettyServer {


    public void run(int port) throws InterruptedException {

        // 接入监听group
        EventLoopGroup boosGroup = new NioEventLoopGroup();

        //数据处理也就是work group
        EventLoopGroup workGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup, workGroup);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

                protected void initChannel(SocketChannel socketChannel) throws Exception {

                    // 获取处理链容器
                    ChannelPipeline channelPipeline = socketChannel.pipeline();
                    //给处理链容器添加处理handler
                    channelPipeline.addLast(new DiscardServerhandler());
                }
            });

            //绑定服务端口
            ChannelFuture channelFuture = serverBootstrap.bind(port);

            //监听服务器关闭
            channelFuture.channel().closeFuture().sync();
        }finally {
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        NettyServer  nettyServer = new NettyServer();
        try {
            nettyServer.run(10241);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
